﻿using PostSharp.Aspects;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace TopUpService.AOP.Aspects
{
    [Serializable]
    public class TransactionWithRetryAspect : MethodInterceptionAspect
    {
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            // transakcija
            using (var scope = new TransactionScope())
            {
                // retry logika
                var retries = 3;
                var succeeded = false;
                while (!succeeded)
                {
                    try
                    {
                        // poslovna logika
                        args.Proceed();

                        // commit transakcije
                        scope.Complete();
                        succeeded = true;
                    }
                    catch
                    {
                        // ne bacaj iznimku dok se ne dosegne max retry count
                        if (retries > 1)
                        {
                            retries--;
                            Debug.WriteLine("retrying due to exception: retries={0}", retries);
                        }
                        else
                            throw;
                    }
                }
            }
        }
    }
}
